<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars" :isLeft="false">
      <template #title></template>
    </GlobalTopBar>
    <image
      class="page_image"
      :src="`${store.imgDomain}login_top2.jpg`"
      mode="scaleToFill"
    />
    <view class="page_content">
      <button
        class="btn"
        v-if="
          !radiovalue ||
          [undefined, 'reject', 'ban'].includes(
            store.subscriptionsSetting[
              'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'
            ],
          ) ||
          [undefined].includes(
            store.subscriptionsSetting[
              'bLdc3rHrTBhaRtDRhYcw5XI6oDOAppWo8C27UPpLT-g'
            ],
          )
        "
        @click="ydFun"
      >
        手机号快捷登录
      </button>
      <button
        v-else
        class="btn"
        type="default"
        open-type="getPhoneNumber"
        @getphonenumber="decryptPhoneNumber"
      >
        手机号快捷登录
      </button>
      <label class="radio" @click="radiovalue = !radiovalue"
        ><radio
          style="transform: scale(0.8)"
          color="#15C8B7"
          value="1"
          :checked="radiovalue"
        /><text
          >我已阅读并同意
          <text
            style="color: #15c8b7"
            @click.stop="
              store.to(
                '/pages/public/agreement?url=wxapp/login/getUserAgreement',
              )
            "
            >《用户协议》</text
          >和
          <text
            style="color: #15c8b7"
            @click.stop="
              store.to(
                '/pages/public/agreement?url=wxapp/login/getPrivacyPolicy',
              )
            "
            >《隐私条款》</text
          ></text
        ></label
      >
      <!-- 其他登录 -->
      <view>
        <view class="qttext"> 其他登录方式 </view>
        <image
          @click="store.to('/pages/masterlogin/index2')"
          class="login_iphone"
          :src="`${store.imgDomain}login_iphone2.jpg`"
          mode="scaleToFill"
        />
      </view>

      <y-drawer
        ref="drawerRef"
        :borderRadius="20"
        :maskClosable="true"
        :length="700"
      >
        <nameimg @hadeorname="gethadeornameFun" />
      </y-drawer>
    </view>
    <!-- 用户端 -->
    <view
      class="toyh flex"
      @click="
        uni.reLaunch({
          url: '/pages/login/index',
        })
      "
    >
      <text>用户端</text>
      <uni-icons
        style="transform: translateY(2rpx)"
        type="right"
        size="20"
        color="#12C2B1"
      ></uni-icons>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useCounterStore } from '@/store';
import request from '@/utils/request';
import nameimg from '../../components/nameimg.vue';

const title = ref('hello');
const store = useCounterStore();
const radiovalue = ref(false);
const btns = ref(null);
const drawerRef = ref(null);
// 获取新用户头像昵称
const gethadeornameFun = (data) => {
  store.nick_name = data.nickname;
  store.headimg = data.headimg;
  doRegister();
};

const isTrue = ref(false);
// 没同意提示
const ydFun = () => {
  clearInterval(store.times);
  store.times = setInterval(() => {
    uni.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log('查询了', res);

        store.subscriptionsSetting = res.subscriptionsSetting;
      },
    });
  }, 1000);

  if (radiovalue.value) {
    if (
      ['reject', 'ban'].includes(
        store.subscriptionsSetting[
          'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'
        ],
      )
    ) {
      uni.showToast({
        title: '请先点击右上角三个点设置订阅消息为允许再登录',
        icon: 'none',
      });
    } else {
      uni.requestSubscribeMessage({
        tmplIds: [
          'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw',
          'bLdc3rHrTBhaRtDRhYcw5XI6oDOAppWo8C27UPpLT-g',
        ], // 替换为实际模板ID，
        success(res) {
          if (res.WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw === 'accept') {
            store.subscriptionsSetting[
              'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'
            ] = 'accept';
            console.log(
              '对不对',
              [undefined, 'reject', 'ban'].includes(
                store.subscriptionsSetting[
                  'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'
                ],
              ),
            );

            uni.showToast({
              title: '订阅完成，请点击按钮登录',
              icon: 'none',
            });
          } else {
            uni.showToast({
              title: '请先订阅消息才可登录',
              icon: 'none',
            });
          }
        },
        fail() {
          uni.showToast({
            title: '请先订阅消息才可登录',
            icon: 'none',
          });
        },
        complete() {},
      });
    }
  } else {
    uni.showToast({
      title: '请先阅读并同意《用户协议》和《隐私条款》',
      icon: 'none',
    });
  }
};

// 获取手机号
const decryptPhoneNumber = async (res) => {
  if (res.detail.code) {
    await getUserPhoneNumber(res.detail.code);
    await loginFun();
  }
};
// 登录
const loginFun = async () => {
  await uni.login({
    provider: 'weixin', //使用微信登录
    success: async function (res) {
      if (store.open_id) {
        doLogin();
        return;
      }
      await getOpenId(res.code);
    },
  });
};

// 通过code获取微信用户Openid
const getOpenId = async (code) => {
  const data = await request('wxapp/login/getOpenId', { code });
  store.open_id = data.openid;
  uni.setStorageSync('open_id', store.open_id);
  doLogin();
};

// 通过code获取微信用户手机号码
const getUserPhoneNumber = async (code) => {
  const data = await request('wxapp/login/getUserPhoneNumber', { code });
  store.phone = data.phone_info.phoneNumber;
  uni.setStorageSync('phone', store.phone);
};

// 登录
const doLogin = async () => {
  const datas = {
    login_type: 1,
    phone: store.phone,
  };
  request('worker/login/doLogin', datas)
    .then((res) => {
      store.workerData = res;
      if (res.status === 2) {
        store.is_type = 2;
        uni.setStorageSync('is_type', 2);
        uni.redirectTo({
          url: '/pages/master/home/index',
        });
      } else {
        store.to('/pages/masterlogin/master');
      }
    })
    .catch((err) => {
      if (err.data.msg === '当前账号不存在,请注册') {
        // store.to('/pages/masterlogin/master');
        uni.showToast({
          title: '暂无师傅信息',
          icon: 'none',
        });
      } else if (err.data.msg === '账号已被禁用') {
        uni.showToast({
          title: '您的账号已被禁用，请联系客服处理',
          icon: 'none',
        });
      }
    });
};
// 个人会员注册
const doRegister = async () => {
  const datas = {
    register_type: 1,
    phone: store.phone,
    nick_name: store.nick_name,
    headimg: store.headimg,
  };
  const data = await request('worker/login/doRegisterWorker', datas);
  uni.redirectTo({
    url: '/pages/home/index',
  });
  store.userInfo = data;
  console.log('注册成功', data);
};
</script>
<style scoped lang="scss">
.page-container {
  position: relative;
  .page_image {
    width: 750rpx;
    height: 597rpx;
  }
}
.page_content {
  overflow-y: auto;
  padding: 126rpx 63rpx 20rpx;
  box-sizing: border-box;
  background-color: #fff;
}
.btn {
  height: 90rpx;
  line-height: 90rpx;
  color: #fff;
  background-color: #15c8b7;
  border-radius: 45rpx;
  font-size: 30rpx;
  text-align: center;
}
.radio {
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  text {
    color: $uni-text-color-grey;
    font-size: 24rpx;
  }
}

.qttext {
  position: relative;
  width: max-content;
  margin: 160rpx auto 25rpx;
  color: $uni-text-color-grey;
  font-size: 24rpx;
  padding: 0 15rpx;
  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #14c8b7;
  }
  &::before {
    content: ' ';
    position: absolute;
    top: 50%;
    right: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #14c8b7;
  }
}
.login_iphone {
  display: block;
  margin: 0 auto;
  width: 89rpx;
  height: 89rpx;
}
.topbars {
  position: fixed;
  width: 100%;
  top: 0;
  left: 0;
  z-index: 9999;
}
.radio {
  width: 100%;
  display: flex;
  align-items: center;
}
.toyh {
  position: absolute;
  bottom: 50rpx;
  right: 40rpx;
  z-index: 2;
  color: #12c2b1;
  font-size: 30rpx;
  .ms_1_img {
    width: 46rpx;
    height: 38rpx;
    margin-right: 10rpx;
  }
}
</style>
